<?php

abstract class ViewSystem {

	protected $prefix = "view";

	protected $file;
    protected $values;
    
    public function __construct( $file, $prefix = null ) {
        $this->file = APP_VIEWS . $file . ".phtml";
        $this->values = array();
        $this->values["base"] = BASE; // Para ajax!!!
        if( $prefix != null )
        	$this->prefix = $prefix;
        return $this;
    }

	public function set($key, $value) {
	    $this->values[$key] = $value;
        return $this;
	}
    
	public function setAll($arr) {
		if ( is_array($arr) && count($arr) > 0 ){
	    	$tmp = array_merge($this->values, $arr);
	    	$this->values = $tmp;
		}
        return $this;
	}
	
	private function clearingRest(&$fileContent) {
		$pattern = "/#\\{(.*)\\}/";
		//$matches = null;
		//preg_match_all($pattern, $fileContent, $matches);
		//print_r($matches);
		$str = preg_replace($pattern, "", $fileContent);
		$fileContent = $str;
	}
	  
	public function output($haveCleanRest = false) {
	    if (!file_exists($this->file)) {
	        return "Error loading template file ($this->file).<br />";
	    }
	    $output = file_get_contents($this->file);
	    
	    foreach ($this->values as $key => $value) {
	        $tagToReplace = "#{{$this->prefix}.{$key}}";
	        $output = str_replace($tagToReplace, $value, $output);
	    }
	    
	    if( $haveCleanRest )
	    	$this->clearingRest($output);
	  
	    return $output;
	}
	
	public function render($haveCleanRest = false) {
		echo $this->output($haveCleanRest);
		exit();
	}
	
}

?>